import CacheConfig from "@/config/CacheConfig";
import StorageUtils from "@/utils/StorageUtils";
import { showInfo } from "@/utils/ToastUtils";
import * as DeviceApi from '@/api/device/index.js';
import * as ReservationApi from '@/api/reservation/index.js';

class AddDeviceService {

	// {code: 'W_SHUIMIAN', codeName: '雷达睡眠监测'},
	// {code: 'W_DIEDAO', codeName: '雷达跌倒监测'},
	// {code: 'B_ECG', codeName: '蓝牙单导心电'},
	// {code: 'B_SPO', codeName: '蓝牙血氧'},
	// {code: 'B_BG', codeName: '蓝牙血糖'},
	// {code: 'B_UA', codeName: '蓝牙尿酸'},
	// {code: 'B_BG_UA_TC', codeName: '血糖/尿酸/总胆固醇'},
	// {code: 'G_BP', codeName: '4G血压'},
	// {code: 'G_BG', codeName: '4G血糖'},
	// {code: 'G_DIEDAO', codeName: '4G跌倒监测'},

	DEVICE_TYPE = {
		"LIGHT": {
			name: "星梦云康智能台灯",
		},
		"B_ECG": {
			name: "蓝牙单导心电",
		},
		"B_SPO": {
			name: "蓝牙血氧"
		},
		"B_BG": {
			name: "蓝牙血糖"
		},
		"B_UA": {
			name: "蓝牙尿酸"
		},
		"B_BG_UA_TC": {
			name: "血糖/尿酸/总胆固醇"
		},
		"W_SHUIMIAN": {
			name: "雷达睡眠监测"
		},
		"W_DIEDAO": {
			name: "雷达跌倒监测"
		},
		"G_BP": {
			name: "4G血压"
		},
		"G_BG": {
			name: "4G血糖"
		},
		"G_DIEDAO": {
			name: "4G跌倒监测"
		}
	}

	constructor() {
		this.uuid = "";
		this.isLight = true;
		this.isSubDevice = false;
		this.isBindUser = true;
		// 主设备
		this.device = {
			deviceId: "",
			deviceType: "",
			deviceName: "",
			productKey: "",
			devicePic: "",
			noteName: "",
		};
		// 子设备
		this.subDevice = {
			deviceId: "",
			deviceType: "",
			deviceName: "",
			productKey: "",
			devicePic: "",
			noteName: "",
		}
	}
	
	scanCodeYangCang(callback) {
		uni.scanCode({
			scanType: 'qrCode',
			success: async (res) => {
				console.log('条码内容：' + res.result);
				this.clear();
				try {
					const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
					this.uuid = userInfo.uuid // "oFhVDvhwLyIxEEpfzpAqP8CwHdZs";
					const codeInfo = JSON.parse(res.result);
					if(codeInfo.deviceType) {
						console.log("设备绑定用户");
						if(codeInfo.deviceType == 'W_OXYGEN') {
							console.log("绑定氧舱设备");
							const param = {
								deviceName: codeInfo.deviceName,
								deviceType: codeInfo.deviceType,
								uuid: this.uuid,
							};
							console.log("设备 param", param);
							DeviceApi.bindDevice(param).then(res => {
								showInfo("绑定成功");
								!!callback && !!callback.yangcanBind();
							})
						} else {
							console.log("绑定其他设备");
							if (codeInfo.deviceType.startsWith("B")) {
								try {
									const bluetoothCount = await this.getBingDeviceCount(this.uuid);
									console.log("当前已绑定蓝牙设备数量：", bluetoothCount);
									if (bluetoothCount >= 4) {
										this.handleError("最多可绑定4台蓝牙设备");
										return;
									}
								} catch (err) {
									console.log("获取蓝牙设备数量失败：", err);
									this.handleError("查询设备信息失败，请重试");
									return;
								}
							}
							console.log("查询设备数量通过==========================================");
							showLoading();
							const param = {
								deviceName: codeInfo.deviceName,
								deviceType: codeInfo.deviceType,
								uuid: this.uuid
							};
							try {
								const checkResult = await DeviceApi.checkBindDevice(param);
								console.log("设备绑定检查结果：", checkResult);
								hideLoading();
								this.init(codeInfo.deviceType, codeInfo.deviceName, codeInfo.productKey);
							} catch (err) {
								console.log("设备绑定检查失败：", err);
								hideLoading();
								this.handleError(err.errMsg);
							}
						}
					} else {
						console.log("绑定氧舱数据");
						const param = {
							oxDeviceName: codeInfo.odn,
							radarDeviceName: codeInfo.rdn,
							uuid: this.uuid,
						};
						StorageUtils.save(CacheConfig.OXYGEN_INFO, param);
						uni.navigateTo({
							url:'/pages/oxygen/notice-book'
						})
					}
				} catch(error) {
					console.log("扫码结果解析失败：", error);
					this.handleError("扫描结果格式错误，请扫描正确的设备二维码");
				}
			},
			fail: (err) => {
				console.log("扫码失败", err);
			}
		})
	}

	scanCode(uuid) {
		uni.scanCode({
			scanType: 'qrCode',
			success: (res) => {
				console.log('条码内容：' + res.result);
				this.clear();
				try {
					const {
						deviceType,
						deviceName,
						productKey
					} = JSON.parse(res.result);
					this.uuid = uuid ? uuid : StorageUtils.get("uuid");
					this.init(deviceType, deviceName, productKey);
				} catch(error) {
					console.log("JSON 解析失败", error);
					this.handleError("扫描结果格式错误");
				}
			},
			fail: (err) => {
				console.log("扫码失败", err);
			}
		})
	}

	scanCodeLight() {
		uni.scanCode({
			scanType: 'qrCode',
			success: (res) => {
				console.log('条码内容：' + res.result);
				try {
					const {
						deviceType,
						deviceName,
						productKey
					} = JSON.parse(res.result);
					const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
					const param = {
						deviceName,
						deviceType,
						uuid: userInfo.uuid
					}
					showLoading();
					DeviceApi.checkBindDevice(param).then(res => {
						console.log("设备绑定检查结果：", res);
						hideLoading();
						this.initLight(deviceType, deviceName, productKey);
					}).catch(err => {
						console.log("设备绑定检查失败：", err);
						hideLoading();
						this.handleError(err.errMsg);
					})
				} catch(error) {
					console.log("扫码结果解析失败：", error);
					this.handleError("扫描结果格式错误，请扫描正确的设备二维码");
				}
			},
			fail: (err) => {
				console.log("扫码失败", err);
			}
		})
	}

	async init(deviceType, deviceName, productKey) {
		const arr = deviceType.split("_");
		console.log("init arr", arr[0]);
		const deviceInfo = await this.getDeviceInfo(deviceName, productKey);
		console.log("init deviceInfo", deviceInfo);
		if(!deviceInfo) {
			this.handleError("获取产品信息失败");
			return;
		}
		switch (arr[0]) {
			case 'LIGHT':
				console.log("添加台灯设备");
				this.device.deviceType = deviceType;
				this.device.deviceName = deviceName;
				this.device.productKey = productKey;
				this.device.devicePic = deviceInfo.devPic;
				this.device.deviceId = deviceInfo.id;
				this.device.noteName = this.DEVICE_TYPE[deviceType].name;
				this.isLight = true;
				this.isSubDevice = false;
				this.isBindUser = true;
				uni.navigateTo({
					url:'/pages/addDevice/resetDevice'
				})
				break;
			case 'B':
				console.log("添加蓝牙设备");
				this.subDevice.deviceType = deviceType;
				this.subDevice.deviceName = deviceName;
				this.subDevice.productKey = productKey;
				this.subDevice.devicePic = deviceInfo.devPic;
				this.subDevice.deviceId = deviceInfo.id;
				this.subDevice.noteName = this.DEVICE_TYPE[deviceType].name;
				this.isLight = false;
				this.isSubDevice = true;
				this.isBindUser = true;
				uni.navigateTo({
					url:'/pages/addDevice/addLamp'
				})
				break;
			case 'G':
				console.log("添加4G设备");
				this.device.deviceType = deviceType;
				this.device.deviceName = deviceName;
				this.device.productKey = productKey;
				this.device.devicePic = deviceInfo.devPic;
				this.device.deviceId = deviceInfo.id;
				this.device.noteName = this.DEVICE_TYPE[deviceType].name;
				uni.navigateTo({
					url:'/pages/addDevice/bindDevice'
				})
				break;
			case 'W':
				console.log("添加WIFI设备");
				this.device.deviceType = deviceType;
				this.device.deviceName = deviceName;
				this.device.productKey = productKey;
				this.device.devicePic = deviceInfo.devPic;
				this.device.deviceId = deviceInfo.id;
				this.device.noteName = this.DEVICE_TYPE[deviceType].name;
				uni.navigateTo({
					url:'/pages/addDevice/configWifiDevice'
				})
				break;
		}
	}

	async initLight(deviceType, deviceName, productKey) {
		const arr = deviceType.split("_");
		console.log("initLight arr", arr[0]);
		const deviceInfo = await this.getDeviceInfo(deviceName, productKey);
		console.log("init deviceInfo", deviceInfo);
		if(!deviceInfo) {
			this.handleError("获取产品信息失败");
			return;
		}
		switch (arr[0]) {
			case 'LIGHT':
				console.log("添加台灯设备");
				this.device.deviceType = deviceType;
				this.device.deviceName = deviceName;
				this.device.productKey = productKey;
				this.device.devicePic = deviceInfo.devPic;
				this.device.deviceId = deviceInfo.id;
				this.device.noteName = this.DEVICE_TYPE[deviceType].name;
				this.isLight = true;
				this.isBindUser = true;
				uni.navigateTo({
					url:'/pages/addDevice/resetDevice'
				})
				break;
			default:
				this.handleError("请扫星梦云康二维码");
				break;
		}
	}
	
	resetLightConfigWifi(info) {
		this.device.deviceId = info.deviceId;
		this.device.deviceName = info.deviceName;
		this.device.productKey = info.productKey;
		this.device.deviceType = "LIGHT";
		this.device.noteName = this.DEVICE_TYPE["LIGHT"].name;
		this.isLight = true;
		this.isSubDevice = false;
		this.isBindUser = false;
		uni.navigateTo({
			url:'/pages/addDevice/resetDevice'
		})
	}
	
	async selectLight(deviceType, deviceName, productKey) {
		console.log("选择台灯设备");
		const deviceInfo = await this.getDeviceInfo(deviceName, productKey);
		console.log("init deviceInfo", deviceInfo);
		this.device.deviceType = deviceType;
		this.device.deviceName = deviceName;
		this.device.productKey = productKey;
		this.device.devicePic = deviceInfo.devPic;
		this.device.deviceId = deviceInfo.id;
		this.device.noteName = this.DEVICE_TYPE[deviceType].name;
	}

	getProductName() {
		if(this.isSubDevice) {
			if(this.isLight) {
				return this.DEVICE_TYPE[this.device.deviceType].name;
			} else {
				return this.DEVICE_TYPE[this.subDevice.deviceType].name;
			}
		} else {
			return this.DEVICE_TYPE[this.device.deviceType].name;
		}
	}
	
	getDeviceInfo(deviceName, productKey) {
		return new Promise((resolve, reject) => {
			DeviceApi.getDeviceInfo({deviceName, productKey}).then(res => {
				console.log("getDeviceInfo success", res);
				resolve(res.obj);
			}).catch(err => {
				console.log("getDeviceInfo error", err);
				resolve();
			})
		})
	}
	
	getBingDeviceCount(uuid) {
		return new Promise((resolve, reject) => {
			if (!uuid) {
				reject(new Error("用户标识为空"));
				return;
			}
			LoginApi.device({
				uuid
			}).then(res => {
				console.log("获取设备列表成功：", res);
				const deviceList = res.obj || [];
				// 统计蓝牙设备数量
				const count = deviceList.filter(v => v.deviceType?.startsWith("B")).length;
				resolve(count);
			}).catch(err => {
				console.error("获取设备列表失败：", err);
				reject(err);
			});
		});
	}
	
	handleError(errorMsg) {
		if (this.toastTimer) {
			clearInterval(this.toastTimer);
			this.toastTimer = null;
		}
		showInfo(errorMsg, 'none', 1800);
		let showCount = 0;
		this.toastTimer = setInterval(() => {
			showCount++;
			if (showCount >= 2) {
				clearInterval(this.toastTimer);
				this.toastTimer = null;
			} else {
				showInfo(errorMsg, 'none', 1800);
			}
		}, 1700);
	}

	clear() {
		this.isLight = true;
		this.isSubDevice = false;
		this.isBindUser = true;
		// 主设备
		this.device = {
			deviceType: "",
			deviceName: "",
			noteName: "",
			productKey: "",
			devicePic: "",
		};
		// 子设备
		this.subDevice = {
			deviceType: "",
			deviceName: "",
			noteName: "",
			productKey: "",
			devicePic: "",
		}
	}

}

export default new AddDeviceService();
